package com.crm.realm;

import com.crm.mapper.EmployeeMapper;
import com.crm.pojo.Employee;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * shiro权限配置类
 */
public class MyRealm extends AuthorizingRealm {

    @Autowired
    EmployeeMapper employeeMapper;

    /**
     * 用户授权方案
     *
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    /**
     * 用户认证方案
     *
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //接收客户端的账户
        System.out.println("===========================进入登录验证方法=======================================");
        String username = authenticationToken.getPrincipal().toString();
        Employee byAccount = employeeMapper.findByAccount(username);
        if (byAccount != null) {
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(byAccount.getEmployeeAccount(), byAccount.getEmployeePassword(), "myRealm");
            //加盐
            info.setCredentialsSalt(ByteSource.Util.bytes(byAccount.getSalt()));
            return info;
        }
        return null;
    }
}
